﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.ComponentModel.Composition;
using System.Web.Security;
using Bzure.Common.Composition;
using Bzure.Common.Core;

namespace Bzure.Security.Principal
{
    public static class UserTicketExtensions
    {
        class TicketDataServicesContainer : MEFContainerBase
        {
            [ImportMany]
            public IEnumerable<Lazy<IContractFactory<ITicketDataService>, IContractMetadata>> TicketDataServices;
            //protected override string MapPath(string virtualPath)
            //{
            //    return HttpContext.Current.Server.MapPath(virtualPath);
            //}
        }
        static TicketDataServicesContainer Container;
        static Dictionary<string, IContractFactory<ITicketDataService>> TicketDataServiceFactories;
        static UserTicketExtensions()
        {
            Container = new TicketDataServicesContainer();
            Container.Compose();
            TicketDataServiceFactories = new Dictionary<string, IContractFactory<ITicketDataService>>();
            foreach (Lazy<IContractFactory<ITicketDataService>, IContractMetadata> factor in Container.TicketDataServices)
            {
                TicketDataServiceFactories[factor.Metadata.ProviderName] = factor.Value;
            }
        }
        public static void SignIn(this BzureUser BzureUser, bool RememberMe)
        {
            string TicketData = string.Empty;
            foreach (IContractFactory<ITicketDataService> aspectFactory in TicketDataServiceFactories.Values)
            {
                if (aspectFactory.Build().BuildTicketData(BzureUser, out TicketData))
                    break;//构造成功，必须退出循环
            }

            UserTicket UserTicket = new Principal.UserTicket()
            {
                User = BzureUser,
                TicketData = TicketData
            };
            FormsAuthenticationTicket ticket =
              new FormsAuthenticationTicket(1, UserTicket.User.UserName,
                  DateTime.Now, DateTime.Now.AddDays(10),
                  RememberMe, UserTicket.ToString());

            string ticketString = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString);
            if (RememberMe)
                cookie.Expires = DateTime.Now.AddDays(10);

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
    public sealed class UserTicket
    {
        public BzureUser User { get; set; }
        public string TicketData { get; set; }
        public static UserTicket Build(string TicketValue)
        {
            string[] vs = TicketValue.Split('#');
            UserTicket ut = new UserTicket();
            if (vs.Length > 6)
            {
                BzureUser user = new BzureUser(vs[1], vs[2])
                {
                    RoleValue = int.Parse(vs[0]),
                    Password = "#",
                    State = int.Parse(vs[3]),
                    OpenID = vs[4],
                    EMail = vs[5],
                    NickName = vs[6]
                };
                ut.User = user;
            }
            if (vs.Length > 7)
            {
                ut.TicketData = vs[7];
            }
            return ut;
        }
        public override string ToString()
        {
            return string.Format("{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}", User.RoleValue, TrimSharp(User.UserID), TrimSharp(User.UserName), User.State, TrimSharp(User.OpenID), TrimSharp(User.EMail), TrimSharp(User.NickName), TrimSharp(this.TicketData));
        }
        static string TrimSharp(string str)
        {
            return str.IsNotNull() ? str.Replace("#", "") : str;
        }

    }


}
